const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
const Router = require('koa-router');
const router = new Router()
const fs = require('fs')
const path = require('path')
app.use(bodyParser())
// let mysql = require('mysql');
// let connection = mysql.createConnection({
//   host: 'localhost',
//   user: 'a123',
//   password: '123456',
//   database: 'mysql1'
// });
// connection.connect();
// response
// app.use(async (ctx, next) => {
//   ctx.body = 'Hello Koa';
// })
//添加信息到数据库
router.post("/addInfo", async (ctx, next) => {
  try {
    const { name, sex, age, width, height } = ctx.request.body
    let res = await new Promise((resolve, reject) => {
      connection.query("select * from presoninfo where name=?", name, (error, results) => {
        if (error) reject(error)
        resolve(results)
      })
    })
    if (res.length === 0) {
      await new Promise((resolve, reject) => {
        connection.query('INSERT INTO presoninfo set ?', { name, sex, age, width, height }, function (error, results) {
          if (error) reject(error);
          console.log(results)
          resolve(results)
        });
      })
      ctx.body = {
        code: 1,
        msg: "添加成功"
      }
    } else {
      ctx.body = {
        code: 2,
        msg: "已经存在该用户的信息了"
      }
    }

  } catch (error) {
    ctx.body = {
      code: 0,
      msg: error
    }
  }
})
//删除接口
router.post("/removeInfo", async (ctx, next) => {
  try {
    const { name } = ctx.request.body;
    const res = await new Promise((resolve, reject) => {
      connection.query("select * from presoninfo where name=?", name, (error, results) => {
        if (error) reject(error)
        resolve(results)
      })
    })
    if (res.length !== 0) {
      await new Promise((resolve, reject) => {
        connection.query("DELETE FROM presoninfo WHERE name=?", [name], (error, result) => {
          if (error) reject(error)
          resolve()
        })
      })
      ctx.body = {
        code: 1,
        msg: "成功删除"
      }
    } else {
      ctx.body = {
        code: 2,
        msg: "该用户不存在"
      }
    }
  } catch (error) {
    ctx.body = {
      code: 0,
      msg: error
    }
  }
})
router.get('/list', (ctx, next) => {
  ctx.body = '列表页'
});

router.post("/upload", async (ctx, next) => {
  let str = '--' + ctx.request.headers['content-type'].split(";")[1].split('=')[1]
  fs.writeFileSync(path.join(__dirname,'./a.txt'),str)
  ctx.body = 'hello world'
})
// app.use(async (ctx,next)=>{
//   ctx.body = 'hello world'
// })
app.use(router.routes())
  .use(router.allowedMethods)
app.listen(3000, () => {
  console.log(`run as http://localhost:3000`)
});